﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace zhangkong
{
    public partial class SignInPage : PhoneApplicationPage
    {
        public static string postback = "";
        public static string postdata = "";

        private string lastStudentID;

        public SignInPage()
        {
            InitializeComponent();

            this.Loaded += SignInPage_Loaded;
        }

        void SignInPage_Loaded(object sender, RoutedEventArgs e)
        {

            ApplicationBar = new ApplicationBar();
            ApplicationBar.BackgroundColor = Colors.Transparent;
            ApplicationBar.ForegroundColor = Colors.White;
            ApplicationBar.Opacity = 0.8;
            ApplicationBar.Mode = ApplicationBarMode.Default;

            ApplicationBarIconButton signInButton = new ApplicationBarIconButton(new Uri("/Toolkit.Content/ApplicationBar.Check.png", UriKind.Relative));
            signInButton.Text = "登录";
            signInButton.Click += signInButton_Click;
            ApplicationBar.Buttons.Add(signInButton);

            ApplicationBarMenuItem helpItem = new ApplicationBarMenuItem();
            helpItem.Text = "常见问题";
            helpItem.Click += helpItem_Click;
            ApplicationBar.MenuItems.Add(helpItem);

            ApplicationBarMenuItem aboutItem = new ApplicationBarMenuItem();
            aboutItem.Text = "关于";
            aboutItem.Click += aboutItem_Click;
            ApplicationBar.MenuItems.Add(aboutItem);
        }
        
        void aboutItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));

        }

        void helpItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
        }

        void signInButton_Click(object sender, EventArgs e)
        {
            
            //验证
            if (ID.Text == "")
            {
                //MessageBox.Show("学号不能为空!");
                SignInTextBlock.Text = "学号不能为空!";
                SignInStoryBoard.Begin();
                return;
            }
            else if (Password.Password == "")
            {
                //MessageBox.Show("密码不能为空！");'
                SignInTextBlock.Text = "密码不能为空！";
                SignInStoryBoard.Begin();
                return;
            }
            else
            {
                postdata = "user=" + ID.Text + "&upwd=" + Register.MD5_BASE64(Password.Password);              //Password.Password;
                //postdata = "user=201213030316&upwd=123123123";
                //verify ueser 
                string uri = "http://202.115.137.129/zhangkong/login.php";
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.BeginGetRequestStream(StreamCallback, httpWebRequest);
            }

            //这里需要异步，就是你肯定懂
            ProgressBar.Visibility = Visibility.Visible;

        }

        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Register.xaml?IsRegister=true", UriKind.Relative));
        }

        //下面进行回调函数
        ///////////////////
        private void StreamCallback(IAsyncResult result)
        {

            HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
            using (Stream stream = httpWebRequest.EndGetRequestStream(result))
            {
                byte[] entryBytes = Encoding.UTF8.GetBytes(postdata);
                stream.Write(entryBytes, 0, entryBytes.Length);
            }

            //这里就和上面GET方法获得回复回调一样，用 private void ResponseCallback(IAsyncResult result) 这个方法。
            httpWebRequest.BeginGetResponse(ResponseCallback, httpWebRequest);
        }
        //第二个回调函数
        private void ResponseCallback(IAsyncResult result)
        {
            Stream stream = null;

            try
            {
                //获取异步操作返回的的信息 
                HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
                //结束对 Internet 资源的异步请求
                WebResponse webResponse = httpWebRequest.EndGetResponse(result);
                stream = webResponse.GetResponseStream();
                //StreamReader sr = new StreamReader(stream, System.Text.UTF8Encoding.UTF8);
                using (StreamReader sr = new StreamReader(stream))
                {
                    postback = sr.ReadToEnd();
                }
            }
            catch 
            {
                Dispatcher.BeginInvoke(() =>
                {
                    //MessageBox.Show("请检查你的网络连接");
                    SignInTextBlock.Text = "请检查你的网络连接！";
                    SignInStoryBoard.Begin();
                    ProgressBar.Visibility = Visibility.Collapsed;
                });
                return;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            if (postback.Length == 5)
            {
                //因为HttpWebRequest是异步，不在UI线程上。所以要改变UI线程上的控件属性就要用Dispatcher.BeginInvoke()。  
                Dispatcher.BeginInvoke(() =>
                {
                    //MessageBox.Show("请检查您的学号和密码", "登录失败", MessageBoxButton.OK);
                    SignInTextBlock.Text = "登录失败请检查您的学号和密码";
                    SignInStoryBoard.Begin();
                    ProgressBar.Visibility = Visibility.Collapsed;
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                {
                    IsolatedStorageSettings.ApplicationSettings["StudentID"] = ID.Text;
                    IsolatedStorageSettings.ApplicationSettings["PassWord"] = Password.Password;
                    IsolatedStorageSettings.ApplicationSettings["RemPassword"] = (RemPasswordTextBlock.Text == "已记住"
                        ? true
                        : false);
                    //IsolatedStorageSettings.ApplicationSettings["RemPassword"] = RemPasswordCheckBox.IsChecked;
                    IsolatedStorageSettings.ApplicationSettings.Save();
                    ProgressBar.Visibility = Visibility.Collapsed;

                    if (lastStudentID != ID.Text)
                    {
                        string password;
                        if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("ID", out password))
                        {
                            IsolatedStorageSettings.ApplicationSettings.Remove("ID");
                        }
                        else if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("StudentPassword", out password))
                        {
                            IsolatedStorageSettings.ApplicationSettings.Remove("StudentPassword");
                        }

                        IsolatedStorageSettings.ApplicationSettings["IsCourseImported"] = false;
                        App.IsCourseImported = false;
                        IsolatedStorageSettings.ApplicationSettings.Save();
                    }


                    SignInTextBlock.Text = "登录成功，正在跳转...";
                    SignInStoryBoard1.Begin();
                });
            }


        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            try
            {
                ID.Text = Convert.ToString(IsolatedStorageSettings.ApplicationSettings["StudentID"]);
                lastStudentID = ID.Text;
                Password.Password = Convert.ToString(IsolatedStorageSettings.ApplicationSettings["Password"]);
            }
            catch (Exception)
            {

            }

            IDictionary<string, string> queryString = NavigationContext.QueryString;
            if (queryString.ContainsKey("logOff"))
            {
                NavigationService.RemoveBackEntry();
            }

        }

        private void MakeAppBarBlack_Focus(object sender, RoutedEventArgs e)
        {
            ApplicationBar.BackgroundColor = Colors.Black;
            ApplicationBar.Opacity = 1;
        }

        private void MakeAppBarTransparent_Focus(object sender, RoutedEventArgs e)
        {
            ApplicationBar.BackgroundColor = Colors.Transparent;
            ApplicationBar.Opacity = 0.8;
        }

        private void SignInSuccess(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CoursePage.xaml?start=true", UriKind.Relative));
        }

        private void RemPassword_Click(object sender, RoutedEventArgs e)
        {
            if (RemPasswordTextBlock.Text == "已记住")
                RemPasswordTextBlock.Text = "未记住";
            else
                RemPasswordTextBlock.Text = "已记住";
        }


        //下面是类尾
    }
}